package org.xiaojl.modules.sys.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.xiaojl.common.SessionUser;
import org.xiaojl.modules.sys.entity.SysUserRole;
import org.xiaojl.modules.sys.mapper.SysUserRoleMapper;
import org.xiaojl.modules.sys.service.SysUserRoleService;
import org.xiaojl.utils.ToolUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

/**
 * <p>
 * 用户角色 服务实现类
 * </p>
 *
 * @author xiaojl
 * @since 2017-08-18
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
	
	@Override
	public String selectRoleIdsByUserId(Long id) {
		Wrapper<SysUserRole> wrapper = new EntityWrapper<SysUserRole>();
		wrapper.eq("userId", id);
		List<SysUserRole> sur = this.selectList(wrapper);
		StringBuffer sb = new StringBuffer("");
		if(sur!=null && sur.size()>0){
			for(SysUserRole r : sur){
				sb.append(r.getRoleId());
				sb.append(",");
			}
		}
		return sb.toString();
	}

	@Override
	public void updateByUserId(Long id, String roleIds, SessionUser su) {
		//删除
		this.delete(new EntityWrapper<SysUserRole>().eq("userId",id));
		
		//添加
		if(ToolUtil.isNotEmpty(roleIds)){
			String[] rids = roleIds.split(",");
			for(int i=0;rids!=null && i<rids.length;i++){
				if(ToolUtil.isNotEmpty(rids[i])){
					SysUserRole ur = new SysUserRole();
					ur.setUserId(id);
					ur.setRoleId(Long.valueOf(rids[i]));
					ur.setCreateBy(su.getSysUser().getId());
					
					this.insert(ur);
				}
			}
		}
	}

	
}
